/*
    Copyright 2010 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.norbl.util;

import java.util.*;

/**
 *
 * @author Barnet Wagman
 */
public class StringUtil {

        /** Elements of argv with the formt <tt>name=value</tt>
         *  are put into a hashmap - names are keys, values are values.
         *  Any elements not in this format are ignored.
         *
         * @param argv
         * @return hashmap of <tt>name=value</tt> elements with <tt>name</tt>
         *  as key and <tt>value</tt> as value.
         */
    public static HashMap<String,String> argvToHt(String[] argv) {

        HashMap<String,String> ht = new HashMap<String, String>();

        NEXT: for ( String arg : argv ) {
            if ( arg == null ) continue NEXT;
            String[] pv = arg.trim().split("=");
            if ( (pv == null) || (pv.length != 2) ) continue NEXT;
            ht.put(pv[0],pv[1]);
        }
        return(ht);
    }

    public static int getNextIndex(HashMap<String,Integer> indexHt, String key) {

        Integer idx = indexHt.get(key);
        if ( idx == null ) {
            idx = new Integer(0);
            indexHt.put(key,idx.intValue());
            return(idx.intValue());
        }
        else {
            int index = idx.intValue() + 1;
            indexHt.put(key,new Integer(index));
            return(index);
        }
    }

        /** Converts a <tt>StackTrace[]</tt> to a <tt>String</tt>, one
         *  item per line.
         */
    public static String stackTraceToString(StackTraceElement[] trace) {
        if ( trace == null ) return("NULL stack trace.");
        String s = "";
        for ( int i = 0; i < trace.length; i++ ) {
            if ( trace[i] != null )
                s += trace[i].toString() + "\n";
            else s += "null trace element at [" + i + "]";
        }
        return(s);
    }

    public static String throwableToString(Throwable x) {
        if ( x == null ) return("NULL exception!");
        return(throwableToString(x,""));
    }

    private static String throwableToString(Throwable x,String prefix) {

        String mess = x.toString() + "\n\n" +
                      stackTraceToString(x.getStackTrace());
        Throwable cause = x.getCause();
        if ( cause != null ) {
            mess += "\nCAUSE:\n" + throwableToString(cause,prefix + "    ");
        }
        return(mess);
    }
}
